package com.example.digitaldiary;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.CursorLoader;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class EditorActivity extends Activity {

	private static final int ACTION_SELECT_SMILEY = 1;
	public static final int ACTION_TAKE_PHOTO = 2;
	private static final int ACTION_SELECT_IMAGE = 3;

	private static final String JPEG_FILE_PREFIX = "IMG_";
	private static final String JPEG_FILE_SUFFIX = ".jpg";

	private String mCurrentPhotoPath;

	private EditText tNoteEdit;
	private TextView tDateView;
	private TextView tView;
	private Context con;
	private DataHelper helper;
	private String entryID = null;
	private String smiley_id = R.drawable.popo04 + "";
	private String tags;
	private String categories;
	private double longtitude;
	private double latitude;
	private String GPSNote;
	private String images = "";
	private String weather;
	private LocationManager locMgr = null;
	private MenuItem menuItem_viewMap;
	private MenuItem menuItem_delete;

	private Gallery gallery;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_editor);
		helper = new DataHelper(this);
		tNoteEdit = (EditText) findViewById(R.id.MULTITEXT);
		tDateView = (TextView) findViewById(R.id.dateTimeTxt);
		gallery = (Gallery) findViewById(R.id.gallery1);
		con = this;
		locMgr = (LocationManager) getSystemService(LOCATION_SERVICE); // initialize
		// service
		DateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		Date date = new Date();
		tDateView.setText(dateformat.format(date));

		// If has string extra loads contents from database
		entryID = getIntent().getStringExtra(MainActivity.ID_EXTRA);
		if (entryID != null) {
			load();
		}

	}

	// Listen GPS fixed Begin
	LocationListener onLocationChange = new LocationListener() {

		@Override
		public void onLocationChanged(Location location) {
			latitude = location.getLatitude();
			longtitude = location.getLongitude();
			// coordinates.setText("Location: " + String.valueOf(latitude) + ","
			// + String.valueOf(longtitude));
			locMgr.removeUpdates(onLocationChange);
			menuItem_viewMap.setVisible(true);
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub

		}

	};
	private MenuItem smiley_item;

	// Listen GPS fixed End
	private void load() {
		// Load contents into fields
		Cursor c = helper.getById(entryID);
		c.moveToFirst();
		tNoteEdit.setText(helper.getNote(c));
		tDateView.setText(helper.getDateCreated(c));
		smiley_id = helper.getSmiley(c);
		tags = helper.getTag(c);
		latitude = helper.getLat(c);
		longtitude = helper.getLon(c);
		categories = helper.getCategory(c);
		images = helper.getImage(c);
		GPSNote = helper.getGPSNote(c);
		weather = helper.getWeather(c);

		if (helper.getImage(c) != null) {

			ImageAdapter imageAdapter = new ImageAdapter(this,
					images.split(";"));
			gallery.setAdapter(imageAdapter);
			gallery.setVisibility(View.VISIBLE);
		}

		// load more contents here
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		helper.close();
	}

	@Override
	protected void onPause() {
		locMgr.removeUpdates(onLocationChange);

		super.onPause();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.save_entry:
			save();
			break;
		case R.id.add_image:
			AlertDialog alertDialog = new AlertDialog.Builder(this)
					.setItems(new String[] { "Take Photo", "Select Photo" },
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									switch (which) {
									case 0:
										dispatchTakePictureIntent(ACTION_TAKE_PHOTO);
										break;
									case 1:
										Intent selectImg = new Intent();
										selectImg
												.setAction(Intent.ACTION_GET_CONTENT);
										selectImg.setType("*/*");
										selectImg
												.addCategory(Intent.CATEGORY_OPENABLE);
										startActivityForResult(selectImg,
												ACTION_SELECT_IMAGE);
										break;
									}
								}
							}).setTitle("Add Image").create();

			alertDialog.show();
			break;
		case R.id.add_tag:

			final Dialog dialog = new Dialog(con);
			dialog.setContentView(R.layout.tag_dialog);
			dialog.setTitle("Add tag");
			final TextView tagNote = (TextView) dialog
					.findViewById(R.id.tagTextView);
			final EditText tagEdit = (EditText) dialog
					.findViewById(R.id.tagEditText);
			final Button tagButton = (Button) dialog
					.findViewById(R.id.dialogButtonOK);
			tagEdit.setText(tags);
			tagButton.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					tags = tagEdit.getText().toString();
					dialog.dismiss();
					tView.setText(tags);
				}
			});

			dialog.show();
			break;

		case R.id.add_category:
			final Dialog categoryDialog = new Dialog(con);
			categoryDialog.setContentView(R.layout.category_dialog);
			categoryDialog.setTitle("Add Category");
			final TextView categoryNote = (TextView) categoryDialog
					.findViewById(R.id.categoryTextView);
			final EditText categoryEdit = (EditText) categoryDialog
					.findViewById(R.id.categoryEditText);
			final Button categoryButton = (Button) categoryDialog
					.findViewById(R.id.categoryButtonOK);
			categoryEdit.setText(categories);
			categoryButton.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					categories = categoryEdit.getText().toString();
					categoryDialog.dismiss();
					tView.setText(categories);
				}
			});
			categoryDialog.show();
		case R.id.view_current_location:

			locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
					onLocationChange);

			break;
		case R.id.view_map:
			Location loc = locMgr
					.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			if (loc != null) {
				Intent callMap = new Intent(this, DiaryMap.class);
				callMap.putExtra(DiaryMap.EXTRA_LATITUDE, loc.getLatitude());
				callMap.putExtra(DiaryMap.EXTRA_LONGITUDE, loc.getLongitude());
				startActivity(callMap);
			} else {
				Log.i("Locnull", "Null");
			}
			break;
		case R.id.select_smiley:
			Intent intent = new Intent(this, SmileyChooserActivity.class);
			startActivityForResult(intent, ACTION_SELECT_SMILEY);
			break;
		case R.id.delete_entry:
			helper.deleteById(entryID);
			finish();
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case ACTION_TAKE_PHOTO:
			if (resultCode == RESULT_OK) {
				handleCameraPhoto();
			}
			break;
		case ACTION_SELECT_SMILEY:
			if (resultCode == RESULT_OK) {
				smiley_id = data.getData().toString();
				smiley_item.setIcon(Integer.parseInt(smiley_id));
			}
			break;
		case ACTION_SELECT_IMAGE:
			/*
			 * if (resultCode == RESULT_OK) {
			 * 
			 * Uri tempUri = data.getData(); String temp =
			 * getPathSelect(tempUri); images = temp; try { FileInputStream
			 * input = new FileInputStream(temp); BufferedInputStream buff = new
			 * BufferedInputStream(input); byte[] bmapArray = new
			 * byte[buff.available()]; buff.read(bmapArray); selectedBitmap =
			 * BitmapFactory.decodeByteArray(bmapArray, 0, bmapArray.length); if
			 * (input != null) { input.close(); } if (buff != null) {
			 * buff.close(); } } catch (FileNotFoundException e) {
			 * 
			 * Log.i("File not found error", e.getMessage()); } catch
			 * (IOException e) { Log.i("IO exception", e.getMessage()); } }
			 */
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public String getPathSelect(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		CursorLoader loader = new CursorLoader(con, uri, projection, null,
				null, null);
		Cursor cursor = loader.loadInBackground();
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_editor, menu);
		menuItem_viewMap = menu.findItem(R.id.view_map);
		menuItem_delete = menu.findItem(R.id.delete_entry);
		if (entryID == null) {
			menuItem_delete.setVisible(false);
			menuItem_viewMap.setVisible(false);
		}
		smiley_item = menu.findItem(R.id.select_smiley);

		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public void onBackPressed() {
		new AlertDialog.Builder(this).setTitle("Really Exit?")
				.setMessage("Do you want to save this entry?")

				.setPositiveButton(android.R.string.yes, new OnClickListener() {

					public void onClick(DialogInterface arg0, int arg1) {
						save();
						EditorActivity.super.onBackPressed();
					}
				})
				.setNegativeButton(android.R.string.no, new OnClickListener() {

					public void onClick(DialogInterface arg0, int arg1) {
						EditorActivity.super.onBackPressed();
					}
				}).create().show();

	}

	public void save() {
		if (entryID == null) {
			helper.insert(tNoteEdit.getText().toString(), tDateView.getText()
					.toString(), images, smiley_id, longtitude, latitude,
					weather, tags, categories, GPSNote);
		} else {
			helper.update(entryID, tNoteEdit.getText().toString(), tDateView
					.getText().toString(), images, smiley_id, longtitude,
					latitude, weather, tags, categories, GPSNote);
		}
		Toast.makeText(getBaseContext(), "Entry Saved", Toast.LENGTH_SHORT)
				.show();
		menuItem_delete.setVisible(true);
	}

	/*
	 * Take photo helper functions
	 */

	public File getAlbumStorageDir(String albumName) {
		return new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				albumName);
	}

	/* Photo album for this application */
	private String getAlbumName() {
		return getString(R.string.album_name);
	}

	private File getAlbumDir() {
		File storageDir = null;

		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {

			storageDir = getAlbumStorageDir(getAlbumName());

			if (storageDir != null) {
				if (!storageDir.mkdirs()) {
					if (!storageDir.exists()) {
						Log.d("CameraSample", "failed to create directory");
						return null;
					}
				}
			}

		} else {
			Log.v(getString(R.string.app_name),
					"External storage is not mounted READ/WRITE.");
		}

		return storageDir;
	}

	private File createImageFile() throws IOException {
		// Create an image file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
				.format(new Date());
		String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
		File albumF = getAlbumDir();
		File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX,
				albumF);
		return imageF;
	}

	private File setUpPhotoFile() throws IOException {

		File f = createImageFile();
		mCurrentPhotoPath = f.getAbsolutePath();

		return f;
	}

	private void galleryAddPic() {
		Intent mediaScanIntent = new Intent(
				"android.intent.action.MEDIA_SCANNER_SCAN_FILE");
		File f = new File(mCurrentPhotoPath);
		Uri contentUri = Uri.fromFile(f);
		mediaScanIntent.setData(contentUri);
		this.sendBroadcast(mediaScanIntent);
	}

	private void dispatchTakePictureIntent(int actionCode) {

		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		File f = null;

		try {
			f = setUpPhotoFile();
			mCurrentPhotoPath = f.getAbsolutePath();
			takePictureIntent
					.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
		} catch (IOException e) {
			e.printStackTrace();
			f = null;
			mCurrentPhotoPath = null;
		}

		startActivityForResult(takePictureIntent, actionCode);
	}

	private void handleCameraPhoto() {

		if (mCurrentPhotoPath != null) {
			images += images.equals("") ? mCurrentPhotoPath : ";"
					+ mCurrentPhotoPath;
			gallery.setAdapter(new ImageAdapter(this, images.split(";")));
			gallery.setVisibility(View.VISIBLE);
			galleryAddPic();
			mCurrentPhotoPath = null;
		}

	}

	public class ImageAdapter extends BaseAdapter {
		Context context;
		String[] images;

		public ImageAdapter(Context c, String[] images) {
			context = c;
			this.images = images;
		}

		@Override
		public int getCount() {
			return images.length;
		}

		@Override
		public Object getItem(int arg0) {
			return arg0;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView mImageView = null;
			if (convertView == null) {
				mImageView = new ImageView(context);
				mImageView.setScaleType(ImageView.ScaleType.FIT_XY);
				mImageView.setLayoutParams(new Gallery.LayoutParams(100, 80));
				mImageView.setPadding(10, 10, 10, 10);

				/* Get the size of the ImageView */
				int targetW = mImageView.getWidth();
				int targetH = mImageView.getHeight();

				/* Get the size of the image */
				BitmapFactory.Options bmOptions = new BitmapFactory.Options();
				bmOptions.inJustDecodeBounds = true;
				BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
				int photoW = bmOptions.outWidth;
				int photoH = bmOptions.outHeight;

				/* Figure out which way needs to be reduced less */
				int scaleFactor = 1;
				if ((targetW > 0) || (targetH > 0)) {
					scaleFactor = Math.min(photoW / targetW, photoH / targetH);
				}

				/* Set bitmap options to scale the image decode target */
				bmOptions.inJustDecodeBounds = false;
				bmOptions.inSampleSize = scaleFactor;
				bmOptions.inPurgeable = true;

				/* Decode the JPEG file into a Bitmap */
				Bitmap bitmap = BitmapFactory.decodeFile(images[position],
						bmOptions);

				/* Associate the Bitmap to the ImageView */
				mImageView.setImageBitmap(bitmap);
			} else {
				mImageView = (ImageView) convertView;
			}

			return mImageView;
		}

	}
}
